package com.hz.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.hz.config.AliyunConfig;
import com.hz.dao.UserDao;
import com.hz.pojo.PicUploadResult;
import com.hz.pojo.User;
import com.hz.service.PicUploadService;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;


@Service
public class PicUploadServiceImpl implements PicUploadService {
    @Resource
    UserDao userDao;
    @Autowired
    private OSS ossClient;

    @Autowired
    private AliyunConfig aliyunConfig;
    @Resource
    StringRedisTemplate stringRedisTemplate;

    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",
            ".jpeg", ".gif", ".png"};

    @Override
    public PicUploadResult upload(MultipartFile uploadFile,String open_id) {

        PicUploadResult fileUploadResult = new PicUploadResult();

        //图片做校验对后缀名
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(),
                    type)) {
                isLegal = true;
                break;
            }
        }
        //封装Result对象，并且将文件的byte数组放置到result对象中
        if (!isLegal) {
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }
        //文件新路径
        String fileName = uploadFile.getOriginalFilename();
        String filePath = getFilePath(fileName);
        // 上传到阿里云
        try {
            //目录结构:images/年/月/日xxx.jsp
            ossClient.putObject(aliyunConfig.getBucketName(), filePath, new
                    ByteArrayInputStream(uploadFile.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
            //上传失败
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }
        fileUploadResult.setStatus("done");
        fileUploadResult.setResponse("success");
        //this.aliyunConfig.getUrlPrefix() + filePath 文件路径需要保存到数据库
        fileUploadResult.setName(this.aliyunConfig.getUrlPrefix() + filePath);
        fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));

        if(open_id!=null){
            try {
                //修改用户头像 并修改缓存内容
                userDao.updUserIcon(fileUploadResult.getName(),open_id);
                String jsonuser = stringRedisTemplate.opsForValue().get(open_id);
                User user = JSONObject.parseObject(jsonuser,User.class);
                user.setUser_icon(fileUploadResult.getName());
                stringRedisTemplate.opsForValue().set(open_id,JSONObject.toJSONString(user));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return  fileUploadResult;
    }

    /**
     * @author lastwhisper
     * @desc 生成路径以及文件名 例如：//images/2019/04/28/15564277465972939.jpg
     * @email gaojun56@163.com
     */
    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        //返回至 阿里云文件路径下
        return "shared_washing_machine/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + System.currentTimeMillis() +
                RandomUtils.nextInt(100, 9999) + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }
}
